#!/usr/bin/python

import os, re

def gnuplot_all(gp, dir, exp="", gp_opts="w lp"):
    """gp, dir, ext, gp_opts -- plot each file in the given directory that matches the expression
    gp : gnuplot instance, start ipython -p numeric
    dir: directory where the plot files are located
    exp: regular expression to match/select plot files
    gp_opts: option for gnuplot e.g. stadard is "w lp"
    """
#    plot_file = filter(lambda fn: fn.endswith(exp), os.listdir(dir))
    pattern = re.compile(exp)
    plot_file = filter(pattern.search, os.listdir(dir))
    if len(plot_file) == 0: return
    plot_file.sort()
    index = 0
    while True:
	gp("plot '%s' %s"%(plot_file[index], gp_opts))
	answer = raw_input("index= %i, continue? +/- "%index).strip()
	if answer == "" or answer == "+":
	    index += 1
	    index = index % len(plot_file)
	elif answer == "-":
	    index -= 1
	    index = index % len(plot_file)
	else: break
